package com.lst.servlet;

import java.io.File;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.CommFun;
import com.lst.dao.ResourcesMapper;
import com.lst.entity.request.ClientReqPara;
import com.lst.entity.response.ClientResPara;
import com.lst.model.MstClient;
import com.lst.model.Resources;
import com.lst.service.MstClientService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: BasicDataServlet
 * @Description: 基础信息接口
 * @author zhanghl
 * @date 2016年11月2日 上午10:18:49
 *
 */
public class BasicDataServlet extends BaseServlet {

	/**
	* @Fields serialVersionUID :
	*/
	private static final long serialVersionUID = 1L;
	
    private MstClientService mstClientService = ctx.getBean(MstClientService.class);
	
	private ResourcesMapper resourcesMapper = ctx.getBean(ResourcesMapper.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();

		ClientResPara resPara = new ClientResPara();

		try {
			ClientReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				Integer userid = Integer.valueOf(reqPara.getUserid());
				String nickname = reqPara.getNickname();
				boolean gender = "1".equals(reqPara.getGender());
				String portrait = reqPara.getPortrait();
				String height = reqPara.getHeight();
				String weight = reqPara.getWeight();
				String aimid = reqPara.getAimid();
				String knowid = reqPara.getKnowid();
				
			  
				String _portrait = "";
				if(!StringUtils.isEmpty(portrait)){
					List<String> urls = dealImgs(portrait, startDate, userid);
					_portrait = urls.get(0);
				}

				MstClient mstclient = new MstClient();

				mstclient.setId(userid);
				mstclient.setNickname(nickname);
				mstclient.setGender(gender);
				mstclient.setPortrait(_portrait);
				mstclient.setUpdatedate(startDate);
				mstclient.setUpdateuser(userid);
				mstclient.setHeight(StringUtils.isEmpty(height) ? null : height);
				mstclient.setWeight(StringUtils.isEmpty(weight) ? null : weight);
				mstclient.setAimid(StringUtils.isEmpty(aimid) ? null : Integer.valueOf(aimid));
				mstclient.setKnowid(StringUtils.isEmpty(knowid) ? null : Integer.valueOf(knowid));

				mstClientService.updateByPrimaryKeySelective(mstclient);

				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
				resPara.setMstClient(mstclient);
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ClientReqPara getReqPara(HttpServletRequest request) {

		ClientReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new ClientReqPara());

			reqPara = (ClientReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String nickname = request.getParameter("nickname");	
			String gender = request.getParameter("gender");
			String portrait = request.getParameter("portrait");
			String height = request.getParameter("height");
			String weight = request.getParameter("weight");
			String aimid = request.getParameter("aimid");
			String knowid = request.getParameter("knowid");

			reqPara.setUserid(userid);
			reqPara.setNickname(nickname);
			reqPara.setGender(gender);
			reqPara.setPortrait(portrait);	
			reqPara.setHeight(height);
			reqPara.setWeight(weight);
			reqPara.setAimid(aimid);
			reqPara.setKnowid(knowid);

		} catch (Exception e) { 
			logger.error("getReqPara error: ", e);
		}
		
		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ClientReqPara registerReqPara = (ClientReqPara) reqPara;
		ClientResPara registerResPara = (ClientResPara) resPara;

		if (StringUtils.isEmpty(registerReqPara.getUserid())) {
			registerResPara.setCode(CommCode.M_A000000);
			registerResPara.setMessage(CommCode.M_P000002);
		} /*else if (StringUtils.isEmpty(registerReqPara.getNickname())) {
			registerResPara.setCode(CommCode.M_A000000);
			registerResPara.setMessage(CommCode.M_C000021);
		} else if (StringUtils.isEmpty(registerReqPara.getWeight())) {
			registerResPara.setCode(CommCode.M_A000000);
			registerResPara.setMessage(CommCode.M_C000014);
		} else if (StringUtils.isEmpty(registerReqPara.getHeight())) {
			registerResPara.setCode(CommCode.M_A000000);
			registerResPara.setMessage(CommCode.M_C000015);
		} else if (StringUtils.isEmpty(registerReqPara.getAimid())) {
			registerResPara.setCode(CommCode.M_A000000);
			registerResPara.setMessage(CommCode.M_C000019);
		} else if (StringUtils.isEmpty(registerReqPara.getKnowid())) {
			registerResPara.setCode(CommCode.M_A000000);
			registerResPara.setMessage(CommCode.M_C000020);
		} */else {
			flag = true;
		}
		
		return  flag;
	}
	
	
	/**
	 * 
	 * @Title: dealImgs
	 * @Description: 处理图片集 
	 * @param @param portrait  
	 * @param @param startDate
	 * @param @param mstClient
	 * @param @return
	 * @param @throws ParseException    设定文件
	 * @return List<String>    返回类型
	 */
	private synchronized List<String> dealImgs(String portrait,Date startDate,Integer userId) throws ParseException{
		//以逗号分分割多张图片
		String [] portraits = portrait.split(",");
		//存放“文件夹 + 图片名称”集
		List<String> urls = new ArrayList<String>();
		//图片资源集
		List<Resources> mstResources = new ArrayList<Resources>();
		//获取时分秒文件夹地址
		String timeAddr = DateUtil.getCurrentTime(DateUtil.ALL_DATE_HORIZONTAL);
		//获取工厂地址
		String facAddr = CommonUtils.getImg_file_path_linux() + timeAddr;

		// 创建工厂文件
		File facFile = new File(facAddr);
		if (!facFile.exists()) {
			facFile.mkdirs();
		}

		String imgName = "";// 图片名称
		String absPath = "";//文件绝对路径
		String relPath = "";//文件相对路径

		// 批量保存图片
		int len = portraits.length;
		for (int i = 0; i < len; i++) {
			
			imgName = DateUtil
					.getCurrentTime(DateUtil.ALL_DATETIME_STRING_QUEUE)
					+ i;

			absPath = facAddr + "/"+ imgName;

			CommFun.base64StringToImage4One(
					portraits[i], absPath);

			relPath = CommCode.RESOURCE_URL_IMAGE + timeAddr +"/"+imgName + ".jpg";
			urls.add(relPath);

			Resources resource = new Resources();
			resource.setCreatedate(startDate);
			resource.setCreateuser(userId);
			resource.setEnabled(true);
			resource.setExtname(".jpg");
			resource.setIsdeleted(false);
			resource.setResname(imgName);
			resource.setRespath(CommCode.RESOURCE_URL_IMAGE + timeAddr +"/");
			resource.setOrderindex(i);
			resource.setOwnerid(userId);
			resource.setOwnertablename("MST_CLIENT");
			resource.setRestype(CommCode.SYSCODE_REOURCES_TYPE_IMAGE);

			mstResources.add(resource);

			logger.info("decPara absPath : " + absPath + "and the index :" + i);
			logger.info("decPara relPath : " + relPath + "and the index :" + i);
		}

		resourcesMapper.saveList(mstResources);

		return urls;

	}

}
